<template>
  <div class="http-server module-container">
    <div class="module-header">
      <h2>HTTP 服务器</h2>
      <p class="module-description">创建本地 HTTP 服务器并模拟 API 响应</p>
    </div>

    <div class="module-content">
      <div class="server-control">
        <el-card>
          <div class="control-header">
            <h3>服务器控制</h3>
            <ConnectionStatus :connected="isRunning" />
          </div>
          
          <el-form label-position="top" size="small">
            <el-form-item label="端口">
              <el-input-number
                v-model="port"
                :min="1"
                :max="65535"
                :disabled="isRunning"
                style="width: 100%"
              />
            </el-form-item>
            
            <el-form-item>
              <el-button
                v-if="!isRunning"
                type="primary"
                @click="startServer"
                icon="el-icon-video-play"
                style="width: 100%"
              >
                启动服务器
              </el-button>
              <el-button
                v-else
                type="danger"
                @click="stopServer"
                icon="el-icon-video-pause"
                style="width: 100%"
              >
                停止服务器
              </el-button>
            </el-form-item>
            
            <el-form-item v-if="isRunning">
              <el-alert
                :title="`服务器地址: http://localhost:${port}`"
                type="success"
                :closable="false"
                show-icon
              />
            </el-form-item>
          </el-form>
        </el-card>
      </div>

      <el-tabs v-model="activeTab">
        <el-tab-pane label="路由配置" name="routes">
          <div class="routes-section">
            <div class="routes-toolbar">
              <el-button type="primary" size="small" @click="addRoute">
                <i class="el-icon-plus"></i> 添加路由
              </el-button>
              <el-button size="small" @click="importRoutes">导入路由</el-button>
              <el-button size="small" @click="exportRoutes">导出路由</el-button>
            </div>

            <el-table :data="routes" style="width: 100%">
              <el-table-column width="40">
                <template slot-scope="scope">
                  <el-checkbox v-model="scope.row.enabled" />
                </template>
              </el-table-column>
              
              <el-table-column prop="method" label="方法" width="100">
                <template slot-scope="scope">
                  <el-select v-model="scope.row.method" size="small">
                    <el-option value="GET" />
                    <el-option value="POST" />
                    <el-option value="PUT" />
                    <el-option value="DELETE" />
                    <el-option value="PATCH" />
                  </el-select>
                </template>
              </el-table-column>
              
              <el-table-column prop="path" label="路径">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.path"
                    placeholder="/api/users"
                    size="small"
                  />
                </template>
              </el-table-column>
              
              <el-table-column prop="status" align="center" label="状态码" width="140">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.status"
                    :min="100"
                    :max="599"
                    size="small"
                    style="width: 120px"
                  />
                </template>
              </el-table-column>
              
              <el-table-column prop="delay" align="center" label="延迟(ms)" width="140">
                <template slot-scope="scope">
                  <el-input-number
                    v-model="scope.row.delay"
                    :min="0"
                    :max="10000"
                    size="small"
                    style="width: 120px"
                  />
                </template>
              </el-table-column>
              
              <el-table-column label="操作" align="center" width="170">
                <template slot-scope="scope">
                  <el-button
                    class="table-action-btn"
                    type="text"
                    size="small"
                    @click="editRoute(scope.row)"
                  >
                    编辑响应
                  </el-button>
                  <el-button
                    class="table-action-btn"
                    type="text"
                    size="small"
                    @click="removeRoute(scope.row.id)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="请求日志" name="logs">
          <div class="logs-section">
            <div class="logs-toolbar">
              <el-button size="small" @click="clearLogs">清空日志</el-button>
              <el-button size="small" @click="exportLogs">导出日志</el-button>
              <el-checkbox v-model="autoScroll">自动滚动</el-checkbox>
            </div>

            <el-table
              :data="requestLogs"
              style="width: 100%"
              height="500"
              ref="logsTable"
            >
              <el-table-column
                prop="timestamp"
                label="时间"
                width="180"
              >
                <template slot-scope="scope">
                  {{ formatTime(scope.row.timestamp) }}
                </template>
              </el-table-column>
              
              <el-table-column prop="method" label="方法" width="80">
                <template slot-scope="scope">
                  <el-tag size="mini" :type="getMethodType(scope.row.method)">
                    {{ scope.row.method }}
                  </el-tag>
                </template>
              </el-table-column>
              
              <el-table-column prop="url" label="URL" show-overflow-tooltip />
              
              <el-table-column prop="ip" label="IP" width="120" />
              
              <el-table-column prop="status" label="响应" width="80">
                <template slot-scope="scope">
                  <span :class="getStatusClass(scope.row.status)">
                    {{ scope.row.status || '-' }}
                  </span>
                </template>
              </el-table-column>
              
              <el-table-column label="操作" width="100">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    size="small"
                    @click="viewLogDetail(scope.row)"
                  >
                    详情
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </el-tab-pane>

        <el-tab-pane label="中间件" name="middleware">
          <div class="middleware-section">
            <el-checkbox-group v-model="enabledMiddleware">
              <el-checkbox label="cors">CORS (跨域支持)</el-checkbox>
              <el-checkbox label="compression">响应压缩</el-checkbox>
              <el-checkbox label="logging">请求日志</el-checkbox>
              <el-checkbox label="rateLimit">速率限制</el-checkbox>
              <el-checkbox label="auth">基础认证</el-checkbox>
            </el-checkbox-group>

            <div class="middleware-config" v-if="enabledMiddleware.includes('cors')">
              <h4>CORS 配置</h4>
              <el-form label-width="120px">
                <el-form-item label="允许的源">
                  <el-input v-model="corsConfig.origin" placeholder="* 或具体域名" />
                </el-form-item>
                <el-form-item label="允许的方法">
                  <el-input v-model="corsConfig.methods" placeholder="GET,POST,PUT,DELETE" />
                </el-form-item>
              </el-form>
            </div>

            <div class="middleware-config" v-if="enabledMiddleware.includes('rateLimit')">
              <h4>速率限制配置</h4>
              <el-form label-width="120px">
                <el-form-item label="时间窗口">
                  <el-input-number v-model="rateLimitConfig.windowMs" :min="1000" /> ms
                </el-form-item>
                <el-form-item label="最大请求数">
                  <el-input-number v-model="rateLimitConfig.max" :min="1" />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </el-tab-pane>
      </el-tabs>
    </div>

    <el-dialog
      title="编辑响应"
      :visible.sync="responseDialog"
      width="600px"
    >
      <el-form label-width="100px">
        <el-form-item label="响应头">
          <el-input
            type="textarea"
            v-model="currentRoute.headers"
            :rows="3"
            placeholder='{"Content-Type": "application/json"}'
          />
        </el-form-item>
        
        <el-form-item label="响应体">
          <el-input
            type="textarea"
            v-model="currentRoute.response"
            :rows="10"
            placeholder='{"message": "Success"}'
          />
        </el-form-item>
      </el-form>
      
      <span slot="footer">
        <el-button @click="responseDialog = false">取消</el-button>
        <el-button type="primary" @click="saveResponse">保存</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
import ConnectionStatus from '@/components/ConnectionStatus.vue'

export default {
  name: 'HttpServer',
  components: {
    ConnectionStatus
  },
  data() {
    return {
      activeTab: 'routes',
      responseDialog: false,
      currentRoute: {},
      autoScroll: true,
      enabledMiddleware: ['cors', 'logging'],
      corsConfig: {
        origin: '*',
        methods: 'GET,POST,PUT,DELETE,OPTIONS'
      },
      rateLimitConfig: {
        windowMs: 60000,
        max: 100
      }
    }
  },
  computed: {
    ...mapState('httpServer', ['isRunning', 'routes', 'requestLogs']),
    port: {
      get() {
        return this.$store.state.httpServer.port
      },
      set(value) {
        this.$store.dispatch('httpServer/updatePort', value)
      }
    }
  },
  methods: {
    ...mapActions('httpServer', [
      'startServer',
      'stopServer',
      'updatePort',
      'addRoute',
      'updateRoute',
      'removeRoute',
      'clearRequestLogs'
    ]),
    
    editRoute(route) {
      // Get the latest route data from store
      const latestRoute = this.routes.find(r => r.id === route.id)
      this.currentRoute = { ...latestRoute }
      this.responseDialog = true
    },
    
    saveResponse() {
      this.updateRoute({
        id: this.currentRoute.id,
        data: this.currentRoute
      })
      this.responseDialog = false
    },
    
    clearLogs() {
      this.clearRequestLogs()
    },
    
    exportLogs() {
      const logs = JSON.stringify(this.requestLogs, null, 2)
      const blob = new Blob([logs], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `server_logs_${Date.now()}.json`
      a.click()
      URL.revokeObjectURL(url)
    },
    
    importRoutes() {
      this.$message.info('导入功能开发中')
    },
    
    exportRoutes() {
      const routes = JSON.stringify(this.routes, null, 2)
      const blob = new Blob([routes], { type: 'application/json' })
      const url = URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = `routes_${Date.now()}.json`
      a.click()
      URL.revokeObjectURL(url)
    },
    
    viewLogDetail(log) {
      this.$message.info('详情功能开发中')
    },
    
    formatTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString()
    },
    
    getMethodType(method) {
      const types = {
        GET: 'success',
        POST: 'primary',
        PUT: 'warning',
        DELETE: 'danger',
        PATCH: 'info'
      }
      return types[method] || 'info'
    },
    
    getStatusClass(status) {
      if (status >= 200 && status < 300) return 'status-success'
      if (status >= 400) return 'status-error'
      return ''
    }
  },
  watch: {
    requestLogs() {
      if (this.autoScroll) {
        this.$nextTick(() => {
          const table = this.$refs.logsTable
          if (table) {
            table.bodyWrapper.scrollTop = 0
          }
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
@import '../../styles/variables.scss';

.http-server {
  .module-content {
    padding: $spacing-large;
  }
  
  .server-control {
    margin-bottom: $spacing-large;
    
    .control-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      margin-bottom: $spacing-medium;
      
      h3 {
        margin: 0;
      }
    }
    
    .server-url {
      code {
        background: $border-extra-light;
        padding: 2px 6px;
        border-radius: 3px;
        color: $primary-color;
      }
    }
  }
  
  .routes-toolbar,
  .logs-toolbar {
    margin-bottom: $spacing-medium;
    display: flex;
    gap: $spacing-base;
    align-items: center;
  }
  
  .middleware-section {
    .el-checkbox-group {
      display: flex;
      flex-direction: column;
      gap: $spacing-base;
    }
    
    .middleware-config {
      margin-top: $spacing-large;
      padding: $spacing-medium;
      background: $border-extra-light;
      border-radius: 4px;
      
      h4 {
        margin-top: 0;
        margin-bottom: $spacing-medium;
      }
    }
  }
  
  .status-success {
    color: $success-color;
  }
  
  .status-error {
    color: $danger-color;
  }
}

.table-action-btn {
  padding-left: 5px !important;
  padding-right: 5px !important;
}
</style>